<template>
  <div id="app">
    <router-view />
  </div>
</template>

<script setup>
import { provide, ref, onMounted } from 'vue'
import VConsole from 'vconsole'
import BigNumber from 'bignumber.js'
let vConsole = new VConsole()
// 全局状态管理，使用 `ref()` 包装以便响应式
const walletState = ref({
  balance: 6.545549,
  currency: 'USDT',
  networkFee: { amount: 27.8599, currency: 'TRX', usdValue: 7.61 },
  fromAddress: '',
  fromLabel: '钱包 A - 账户 01'
})

// 提供 `walletState`，使其在其他组件中可被注入并修改
provide('walletState', walletState)

const address = ref('')
const usdtBalance = ref('0')
const USDT_CONTRACT_ADDRESS = 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t'


onMounted(async () => {
  console.log('onMounted');
  // return;
  const okxTron = window.okxwallet?.tronLink
  if (!okxTron) {
    console.warn('OKX Tron 钱包未注入')
    return
  }

  // 请求授权
  let tron_requestAccounts =  await okxTron.request({ method: 'tron_requestAccounts' })
  console.log('tron_requestAccounts',tron_requestAccounts)
  // 获取地址
  const walletAddr = okxTron.tronWeb?.defaultAddress?.base58
  if (walletAddr) {
    address.value = walletAddr
    walletState.value.fromAddress = address.value  // 更新 `walletState` 中的地址
    await fetchUsdt()
  }

  // 监听地址变更
  window.addEventListener('message', e => {
    console.log('accountsChanged')
    if (e.data?.message?.action === 'accountsChanged') {
      const newAddr = e.data.message.data.address
      if (newAddr) {
        address.value = newAddr
        fetchUsdt()
      }
    }
  })
  // 监听交易hash
  window.addEventListener('message', (e) => {
  if (e.data?.message?.action === 'transaction') {
    console.log('transaction')
    const { status, hash } = e.data.message.data
    if (status === 'success') {
      console.log('交易成功，哈希:', hash)
    } else if (status === 'failed') {
      console.log('交易失败')
    }
  }
})
})
async function fetchUsdt() {
  if (!address.value) {
    console.warn('地址为空，跳过 USDT 获取')
    return
  }
  const tronWeb = window.okxwallet.tronLink.tronWeb
  const contract = await tronWeb.contract().at(USDT_CONTRACT_ADDRESS)
  const raw = await contract.methods.balanceOf(address.value).call()
  const rawHex = raw._hex
  usdtBalance.value = new BigNumber(rawHex).dividedBy(1e6).toFixed(2)
  walletState.value.balance = usdtBalance.value  // 更新 `walletState` 中的余额
}
</script>

<style>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', sans-serif;
  background-color: #f5f5f5;
  color: #333;
}

#app {
  min-height: 100vh;
  overflow-x: hidden;
}
</style>